package com.chen.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * com.example.demo.filter
 * 作者      : 陈晓
 * 描述      : 验证是否实现登录
 * 创建日期  : 2018/4/28
 * 修改日期  :
 */
public class LoginInterceptor implements Filter {

  private final String loginUrl = "/index/login";
  private final String staicResources1 = "/resources";



  public void init(FilterConfig filterConfig) throws ServletException {

  }

  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    String requestURI = request.getRequestURI();
    if (requestURI.equals("/")||requestURI.indexOf(loginUrl) > -1 || requestURI.indexOf(staicResources1) > -1) {
      chain.doFilter(request, response);
      return;
    }
    Object currentUser = request.getSession().getAttribute("loginUser");
    if (currentUser == null) {
      response.sendRedirect(loginUrl);
    }
    chain.doFilter(request, response);
  }

  public void destroy() {

  }
}
